/**
 * 日期格式化函数
 * @param {string|number|Date} date 要格式化的日期
 * @param {string} format 格式化模式，例如：'YYYY-MM-DD HH:mm:ss'
 * @returns {string} 格式化后的日期字符串
 */
export function formatDate(date, format = "YYYY-MM-DD HH:mm:ss") {
  if (!date) return "";

  const d = new Date(date);
  if (isNaN(d.getTime())) return "";

  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  const day = d.getDate();
  const hours = d.getHours();
  const minutes = d.getMinutes();
  const seconds = d.getSeconds();

  const formatMap = {
    YYYY: year,
    MM: padZero(month),
    DD: padZero(day),
    HH: padZero(hours),
    mm: padZero(minutes),
    ss: padZero(seconds),
  };

  return format.replace(/(YYYY|MM|DD|HH|mm|ss)/g, (match) => formatMap[match]);
}

/**
 * 数字补零函数
 * @param {number} num 要补零的数字
 * @returns {string} 补零后的字符串
 */
function padZero(num) {
  return String(num).padStart(2, "0");
}

/**
 * 获取相对时间描述
 * @param {string|number|Date} date 要计算的日期
 * @returns {string} 相对时间描述
 */
export function getRelativeTime(date) {
  if (!date) return "";

  const d = new Date(date);
  if (isNaN(d.getTime())) return "";

  const now = new Date();
  const diff = now.getTime() - d.getTime();
  const diffMinutes = Math.floor(diff / (1000 * 60));
  const diffHours = Math.floor(diff / (1000 * 60 * 60));
  const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (diffMinutes < 1) return "刚刚";
  if (diffMinutes < 60) return `${diffMinutes}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 30) return `${diffDays}天前`;

  return formatDate(date, "YYYY-MM-DD");
}

/**
 * 获取日期范围
 * @param {string} range 范围类型：'today' | 'yesterday' | 'week' | 'month' | 'year'
 * @returns {[Date, Date]} 开始日期和结束日期
 */
export function getDateRange(range) {
  const now = new Date();
  const start = new Date();
  const end = new Date();

  switch (range) {
    case "today":
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      break;
    case "yesterday":
      start.setDate(start.getDate() - 1);
      start.setHours(0, 0, 0, 0);
      end.setDate(end.getDate() - 1);
      end.setHours(23, 59, 59, 999);
      break;
    case "week":
      start.setDate(start.getDate() - start.getDay());
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      break;
    case "month":
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      break;
    case "year":
      start.setMonth(0, 1);
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      break;
    default:
      break;
  }

  return [start, end];
}
